package com.base.library.ext

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.coroutineScope
import com.base.library.coroutine.mainSupervisor
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun <T> MutableSharedFlow<T>.send(value: T) {
    mainSupervisor {
        emit(value)
    }
}


fun <T> Flow<T>.listenTo(
    lifecycle: Lifecycle,
    collector: FlowCollector<T>
) {
    lifecycle.coroutineScope.launch(Dispatchers.Main) {
        collect(collector)
    }
}

fun CoroutineScope.countDownCoroutines(
    total: Int,
    onTick: (Int) -> Unit,
    onStart: (() -> Unit)? = null,
    onFinish: (() -> Unit)? = null,
): Job {
    return flow {
        for (i in total downTo 0) {
            emit(i)
            delay(1000)
        }
    }.flowOn(Dispatchers.Main)
        .onStart { onStart?.invoke() }
        .onCompletion { onFinish?.invoke() }
        .onEach { onTick.invoke(it) }
        .launchIn(this)
}

fun <T> MutableStateFlow<T?>.listenTo(
    data: LiveData<T?>,
    onChange: ((data: T?) -> Unit)? = null
) {
    data.observeForever {
        this.value = it
        onChange?.invoke(it)
    }
}

fun <T> MutableLiveData<T?>.listenTo(
    data: MutableLiveData<T?>,
    onChange: ((data: T?) -> Unit)? = null
) {
    data.observeForever {
        this.value = it
        onChange?.invoke(it)
    }
}